package han.fetch;

import han.proof.Cookie;
import han.proof.CookieRepository;
import han.sql.InsertThread;
import han.thread.CustomThread;
import han.thread.MonitorThread;
import han.util.ListTool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author: Han
 * @date: 2018/7/12 10:14
 * @dscription: 获取投资机构id
 */
class InvestOrganizationId {

    private Object krLock = new Object();
    private CookieRepository cookieRepository;

    InvestOrganizationId(CookieRepository cookieRepository) {
        this.cookieRepository = cookieRepository;
    }

    void threadStart() {
        //页码list
        List<Integer> pageList = generatePageList();
        //分割
        List<List<Integer>> splitList = new ListTool<Integer>().splitListBySize(pageList, 122);
        //cookie list
        List<Cookie> cookieList = cookieRepository.getCookieList();
        //线程池
        ThreadPoolExecutor executor = new CustomThread();
        //数据库插入对象
        InsertThread insertThread = new InsertThread();
        //提交线程
        executor.submit(insertThread);
        //监控线程
        MonitorThread monitorThread = new MonitorThread(insertThread, executor, cookieRepository);
        executor.submit(monitorThread);
        for (int i = 0; i < splitList.size() && i < cookieList.size(); i++) {
            //每个page list分配一个cookie
            Cookie cookie = cookieList.get(i);
            List<Integer> tempPageList = splitList.get(i);
            InvestOrganizationIdThread investOrganizationIdThread = new InvestOrganizationIdThread(tempPageList,
                    cookie, insertThread, krLock);
            executor.submit(investOrganizationIdThread);
        }
        //等待线程停止
        executor.shutdown();
    }

    /**
     * 生成投资机构页数
     *
     * @return 页数list
     */
    private List<Integer> generatePageList() {
        List<Integer> list = new ArrayList<>();
        int totalPages = 2641;
        for (int i = 1; i <= totalPages; i++) {
            list.add(i);
        }
        return list;
    }
}
